package it.xiuxian.dagongyuzhou.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

import it.xiuxian.dagongyuzhou.R;
import it.xiuxian.dagongyuzhou.presenter.WXEntryActivityPresenter;
import it.xiuxian.lib.base.ArouterAddress;
import it.xiuxian.lib.base.BaseActivity;
import it.xiuxian.lib.http.HttpConfig;
import it.xiuxian.lib.utils.EncodeUtils;
import it.xiuxian.lib.utils.SPUtil;
import it.xiuxian.lib.utils.ToastUtil;
import it.xiuxian.personcenter.bean.Constant;
@Route(path = ArouterAddress.WXENTRYACTIVITY)
public class WXEntryActivity extends BaseActivity<WXEntryActivityPresenter> implements IWXAPIEventHandler {
    private IWXAPI api;
    private MyHandler handler;
    private static final String TAG = "WXEntryActivity";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public WXEntryActivityPresenter getPresenter() {
        return new WXEntryActivityPresenter();
    }



    private static class MyHandler extends Handler {
        private final WeakReference<WXEntryActivity> wxEntryActivityWeakReference;

        public MyHandler(WXEntryActivity wxEntryActivity){
        wxEntryActivityWeakReference = new WeakReference<WXEntryActivity>(wxEntryActivity);
    }

    @Override
    public void handleMessage(Message msg) {
        int tag = msg.what;
        switch (tag) {
            case 1: {
                Bundle data = msg.getData();
                JSONObject json = null;
                try {
                    json = new JSONObject(data.getString("result"));
                    String openId, accessToken, refreshToken, scope;
                    openId = json.getString("openid");
                    accessToken = json.getString("access_token");
                    refreshToken = json.getString("refresh_token");
                    scope = json.getString("scope");
                  /* Intent intent = new Intent(wxEntryActivityWeakReference.get(), SendToWXActivity.class);
                    intent.putExtra("openId", openId);
                    intent.putExtra("accessToken", accessToken);
                    intent.putExtra("refreshToken", refreshToken);
                    intent.putExtra("scope", scope);
                    wxEntryActivityWeakReference.get().startActivity(intent);*/
                } catch (JSONException e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        }
    }
}

    @Override
    public void initView() {
       // super.initView();
        api = WXAPIFactory.createWXAPI(this, Constant.APP_ID, false);
        //ToastUtil.Companion.showShort("我进来了");
        handler = new MyHandler(this);
        try {
            Intent intent = getIntent();
            api.handleIntent(intent, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onReq(BaseReq baseReq) {
        switch (baseReq.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                break;
            default:
                break;
        }

    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(final BaseResp resp) {
        int result = 0;
        if(resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX){
            //ToastUtil.Companion.showShort("wojianlia");
            try {
                JSONObject json1 = new JSONObject();
                String id = SPUtil.Companion.get("id","");
                //ToastUtil.Companion.showShort("id的值:"+id);
                //LogUtils.d("id的值:"+id);
                json1.put("id", id);
                OkGo.<String>post(HttpConfig.BASE_URL + "/appzixun/fenxiang")
                        .params("encrypt", EncodeUtils.encodeAES(json1.toString()))
                        .execute(new StringCallback(){
                            @Override
                            public void onSuccess(Response<String> response) {
                              //  LogUtils.e("我进来了",new Throwable());
                                finish();
                            }
                        });
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        //Toast.makeText(this, "baseresp.getType = " + resp.getType(), Toast.LENGTH_SHORT).show();
        //成功后发送请求
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result = 1;
                final String code = ((SendAuth.Resp) resp).code;//需要转换一下才可以

                try { JSONObject json1 = new JSONObject();
                    json1.put("code",code);
                    OkGo.<String>post(HttpConfig.BASE_URL + "/apptixian/bangWeChat")
                            .params("encrypt", EncodeUtils.encodeAES(json1.toString()))
                            .execute(new StringCallback(){

                                @Override
                                public void onSuccess(Response<String> response){
                                            Log.e("response",response.body());
                                    JSONObject json = null;
                                    try {
                                        json = new JSONObject(response.body());
                                        int code= json.getInt("code");
                                        String msg = json.getString("msg");
                                        if(code==0){
                                            ToastUtil.Companion.showShort(msg);
                                            ARouter.getInstance().build(ArouterAddress.SHIMINGACTIVITY).navigation();
                                            finish();
                                        } else {
                                            ToastUtil.Companion.showShort(msg);
                                            finish();
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }


                                }
                            });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
              //  ToastUtil.Companion.showShort("发送取消");
                result = 2;
                finish();// 发送取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
               // ToastUtil.Companion.showShort("发送被拒绝");
                finish();
                result = 3;   // 发送被拒绝
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
               // ToastUtil.Companion.showShort("不支持错误");
                finish();
                result = 4;  // 不支持错误
                break;
            default:
               // ToastUtil.Companion.showShort("发送返回");
                finish();
                result = 5;  // 发送返回
                break;
        }
       // Toast.makeText(this, result, Toast.LENGTH_LONG).show();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

}
